import { Key, useRef, useState } from "react"
import { SysUser } from "@sker/model"
import { App, Button, Card, Dropdown, Empty, Input, Modal, Popconfirm, message } from "antd"
import { UserAdd } from "./user-add"
import { UserGroupSelector } from "./user-group-selector"
import ProTable, { ActionType } from "@ant-design/pro-table"
import { PlusOutlined } from "@ant-design/icons"
import type { CrudFilters } from "@refinedev/core"
import { BetaSchemaForm } from "@ant-design/pro-form"
import { useProTable, useAxiosWebPost, useModel, useModal } from '@sker/sdk';
export const UserSelector: React.FC<{ placeholder?: string, multi?: boolean, value?: Key[], onSelect?: (record: string[]) => void }> = ({ multi, value, onSelect }) => {
    const model = useModel(SysUser)
    const { fetch: addUser, loading: addUserLoading } = useAxiosWebPost('imeepos/core/user/add', {})
    const { props: modalProps, setOpen, setTitle } = useModal('添加用户')
    const [editRecord, setEditRecord] = useState<any>()
    const [keyword, setKeyword] = useState<string>()
    const [userGroup, setUserGroup] = useState<any[]>([])
    const { props: proTableProps, actionRef, onChange } = useProTable(multi ? 'checkbox' : 'radio', value);
    const { props: realnameModalProps, setOpen: setRealnameModalOpen, extra } = useModal('完善姓名')
    const { props: mobileModalProps, setOpen: setMobileModalOpen, extra: mobileExtra } = useModal('完善手机号')
    const sysUser = useModel(SysUser)

    onChange((keys, rows) => {
        onSelect(keys);
    })
    return <div className="flex">
        <Modal {...mobileModalProps}>
            <BetaSchemaForm onFinish={async (values) => {
                if (!mobileExtra.uid) return App.useApp().message.error(`参数错误`)
                await sysUser.update(values, mobileExtra.uid, ['uid'])
                setMobileModalOpen(false, null)
                actionRef.current?.reload();
            }} columns={[
                { title: '手机号', dataIndex: 'mobile' }
            ]} />
        </Modal>
        <Modal {...realnameModalProps}>
            <BetaSchemaForm onFinish={async (values) => {
                if (!extra.uid) return App.useApp().message.error(`参数错误`)
                await sysUser.update(values, extra.uid, ['uid'])
                setRealnameModalOpen(false, null)
                actionRef.current?.reload();
            }} columns={[
                { title: '姓名', dataIndex: 'realname' }
            ]} />
        </Modal>
        <Modal {...modalProps}>
            <UserAdd value={editRecord} onFinish={async (values) => {
                let group_id: string | null = null;
                if (userGroup && userGroup.length > 0) {
                    group_id = userGroup[0].id;
                }
                await addUser({
                    ...values,
                    group_id: group_id
                })
                setOpen(false)
                setEditRecord(null)
                actionRef.current?.reload();
            }} />
        </Modal>
        <div className="w-400px">
            <UserGroupSelector multi={false} onSelect={record => setUserGroup(record)} />
        </div>
        <Card title={'用户列表'}
            className="flex-1 ml-24px"
            extra={<div className="flex center">
                <Input.Search placeholder="请输入用户名或姓名" onSearch={e => setKeyword(e)} />
                <Button className="ml-8px" type={'primary'} size={'small'} icon={<PlusOutlined />} onClick={() => {
                    setEditRecord(null)
                    setOpen(true)
                }}></Button>
            </div>}
        >
            <ProTable
                {...proTableProps}
                rowKey={record => {
                    return record.username
                }}
                loading={addUserLoading}
                params={{
                    group_id: userGroup.map(it => it.id),
                    keyword,
                    addUserLoading
                }}
                columns={[
                    { title: '用户名', dataIndex: 'username', },
                    {
                        title: '手机号',
                        dataIndex: 'mobile',
                        render(dom, entity, index, action, schema) {
                            return <Button type={'link'} onClick={e => {
                                setMobileModalOpen(true, { uid: entity.uid })
                            }}>{dom}</Button>
                        },
                    },
                    {
                        title: '姓名',
                        dataIndex: 'realname',
                        render(dom, entity, index, action, schema) {
                            return <Button type={'link'} onClick={e => {
                                setRealnameModalOpen(true, { uid: entity.uid })
                            }}>{dom}</Button>
                        },
                    },
                    {
                        title: '操作',
                        hideInSearch: true,
                        align: 'right',
                        render: (dom, entity, index, action, schema) => {
                            return <>
                                <Button size={'small'} type={'link'} onClick={e => {
                                    setEditRecord(entity)
                                }}>详情</Button>
                                <Button size={'small'} type={'link'} onClick={e => {
                                    setTitle('编辑用户')
                                    setOpen(true)
                                    setEditRecord(entity)
                                }}>编辑</Button>
                                <Popconfirm onConfirm={async e => {
                                    await model.delete(entity.uid)
                                    await actionRef.current?.reload();
                                }} title={'此操作不可逆!您确定要执行此操作吗？'} description={'删除后无法恢复，请慎重操作！！'}>
                                    <Button size={'small'} type={'link'} danger >删除</Button>
                                </Popconfirm>
                            </>
                        }
                    }
                ]} request={async (params, sort, filter) => {
                    const filters: CrudFilters = [];
                    if (params.group_id && params.group_id.length > 0) {
                        filters.push({ field: 'group_id', operator: 'in', value: params.group_id })
                    }
                    if (params.keyword) {
                        filters.push({
                            operator: 'or',
                            value: [
                                { field: 'username', operator: 'contains', value: params.keyword },
                                { field: 'realname', operator: 'contains', value: params.keyword },
                                { field: 'mobile', operator: 'contains', value: params.keyword },
                            ]
                        })
                    }
                    return model.find(['uid', 'username', 'realname', 'mobile'], [
                        ...filters,
                    ], [{ field: 'create_date', order: 'desc' }], { current: params.current, pageSize: params.pageSize })
                }} />
        </Card>
    </div>
}
